package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"web_end/forms"
	"web_end/global/response"
	"web_end/proto"
	"web_end/utils"
)

// HandleTaskResponse /* 处理任务响应
func HandleTaskResponse(raw *proto.TaskResponseInfo) *response.TaskResponse {
	return &response.TaskResponse{
		TaskId:   raw.Id,
		TaskName: raw.Name,
		Grade:    raw.Grade,
		Status:   raw.Status,
	}
}

// CreateTask /* 创建任务
func CreateTask(ctx *gin.Context) {
	errLogger := utils.NewErrorLogger("CreateTask")
	var createTaskForm forms.CreateTaskForm
	if err := ctx.ShouldBindJSON(&createTaskForm); err != nil {
		errLogger("创建", "任务", "参数错误")
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}

	userServerClient := *utils.CreateUserServerGrpc("CreateTask", "创建任务")
	// 如果设置了任务所属人，判断该用户是否存在
	if createTaskForm.OwnerId != 0 {
		_, err := userServerClient.GetUserById(ctx, &proto.IdRequest{UserId: createTaskForm.OwnerId})
		if err != nil {
			errLogger("查询", "用户", "用户不存在")
			utils.HandleGrpcErrorToHttp(err, ctx)
			return
		}
	}
	// 判断创建者是否存在
	if _, err := userServerClient.GetUserById(ctx, &proto.IdRequest{UserId: createTaskForm.CreatorId}); err != nil {
		errLogger("查询", "用户", "用户不存在")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	projectServerClient := *utils.CreateProjectGrpc("CreateTask", "创建任务")
	rsp, err := projectServerClient.CreateTask(ctx, &proto.CreateTaskInfo{
		Name:        createTaskForm.TaskName,
		Grade:       createTaskForm.Grade,
		Status:      createTaskForm.Status,
		CreatorId:   createTaskForm.CreatorId,
		IterationId: createTaskForm.IterationId,
		GroupId:     createTaskForm.GroupId,
	})
	if err != nil {
		errLogger("创建", "任务", "grpc操作失败")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	data := HandleTaskResponse(rsp)
	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
		"data": data,
	})
}

// GetTaskById /* 通过任务ID查询任务
func GetTaskById(ctx *gin.Context) {
	errLogger := utils.NewErrorLogger("GetTaskById")
	taskIdStr := ctx.Param("id")
	taskIdInt, err := strconv.Atoi(taskIdStr)
	if err != nil {
		errLogger("查询", "任务", "参数错误")
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}

	projectServerClient := *utils.CreateProjectGrpc("GetTaskById", "查询任务")
	rsp, err := projectServerClient.GetTaskById(ctx, &proto.TaskIdInfo{Id: uint64(taskIdInt)})
	if err != nil {
		errLogger("查询", "任务", "grpc操作错误")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	data := HandleTaskResponse(rsp)
	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
		"data": data,
	})
}

// GetTaskListByIterationId /* 通过迭代ID查询任务列表
func GetTaskListByIterationId(ctx *gin.Context) {
	errLogger := utils.NewErrorLogger("GetTaskListByIterationId")
	iterationIdStr := ctx.Param("id")
	iterationIdInt, err := strconv.Atoi(iterationIdStr)
	if err != nil {
		errLogger("查找", "任务列表", "参数错误")
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}
	projectServerClient := *utils.CreateProjectGrpc("GetTaskListByIterationId", "查询任务列表")
	rsp, err := projectServerClient.GetTaskListByIterationId(ctx, &proto.IterationIdInfo{Id: uint64(iterationIdInt)})
	if err != nil {
		errLogger("查找", "任务列表", "grpc操作错误")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	var taskList []response.TaskResponse
	for _, task := range rsp.TaskList {
		taskList = append(taskList, *HandleTaskResponse(task))
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
		"data": taskList,
	})
}

// UpdateTask /* 更新任务
func UpdateTask(ctx *gin.Context) {
	errLogger := utils.NewErrorLogger("UpdateTask")
	var updateTaskForm forms.UpdateTaskForm
	if err := ctx.ShouldBindJSON(&updateTaskForm); err != nil {
		errLogger("更新", "任务", "参数错误")
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}

	if updateTaskForm.OwnerId != 0 {
		userServerClient := *utils.CreateUserServerGrpc("UpdateTask", "更新任务")
		_, err := userServerClient.GetUserById(ctx, &proto.IdRequest{UserId: updateTaskForm.OwnerId})
		if err != nil {
			errLogger("查询", "用户", "目标用户不存在")
			utils.HandleGrpcErrorToHttp(err, ctx)
			return
		}
	}

	projectServerClient := *utils.CreateProjectGrpc("UpdateTask", "更新任务")
	_, err := projectServerClient.UpdateTask(ctx, &proto.UpdateTaskInfo{
		Id:      updateTaskForm.TaskId,
		Name:    updateTaskForm.TaskName,
		Grade:   updateTaskForm.Grade,
		Status:  updateTaskForm.Status,
		OwnerId: updateTaskForm.OwnerId,
		UserId:  updateTaskForm.UserId,
		GroupId: updateTaskForm.GroupId,
	})
	if err != nil {
		errLogger("更新", "任务", "grpc操作错误")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
	})
}

// DeleteTask /* 删除任务
func DeleteTask(ctx *gin.Context) {
	errLogger := utils.NewErrorLogger("DeleteTask")
	var deleteTaskForm forms.DeleteTaskForm
	if err := ctx.ShouldBindJSON(&deleteTaskForm); err != nil {
		errLogger("删除", "任务", "参数错误")
		ctx.JSON(http.StatusOK, gin.H{
			"code": response.CodeBadRequest,
			"msg":  response.MsgParamsError,
		})
		return
	}

	projectServerClient := *utils.CreateProjectGrpc("DeleteTask", "删除任务")
	_, err := projectServerClient.DeleteTask(ctx, &proto.DeleteTaskInfo{
		Id:      deleteTaskForm.TaskId,
		UserId:  deleteTaskForm.UserId,
		GroupId: deleteTaskForm.GroupId,
	})
	if err != nil {
		errLogger("删除", "任务", "grpc操作错误")
		utils.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": response.CodeOk,
		"msg":  response.MsgSuccess,
	})
}
